package com.xckj.cycling.presenter;

import androidx.annotation.NonNull;
import com.xckj.cycling.bean.BaseBean;
import com.xckj.cycling.bean.UserInfoResponseBean;
import com.xckj.cycling.context.AppContext;
import com.xckj.cycling.framework.net.RetrofitManager;
import com.xckj.cycling.global.Constant;
import com.xckj.cycling.iview.ILoginView;
import com.xckj.cycling.utils.SpUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.Objects;

/**
 * @Author: ChenYao
 * @Describe: 登录
 * @Date: 2023/3/5 09:52
 */
public class LoginPresenter {
    private final ILoginView loginView;

    public LoginPresenter(ILoginView loginView) {
        this.loginView = loginView;
    }

    /**
     * 登录
     *
     * @param account  账号
     * @param password 密码
     */
    public void login(String account, String password) {
        loginView.showLoading();
        SpUtil.put(AppContext.globalContext(), Constant.LAST_EMAIL, account);
        Call<BaseBean<UserInfoResponseBean>> call = RetrofitManager.getInstance().getService().login(account, password);
        call.enqueue(new Callback<BaseBean<UserInfoResponseBean>>() {
            @Override
            public void onResponse(@NonNull Call<BaseBean<UserInfoResponseBean>> call, @NonNull Response<BaseBean<UserInfoResponseBean>> response) {
                if (response.isSuccessful()) {
                    BaseBean<UserInfoResponseBean> baseBean = response.body();
                    if (Constant.SUCCESS_CODE == Objects.requireNonNull(baseBean).code) {
                        loginView.loginSuccess(baseBean.data.getUserinfo());
                    } else {
                        loginView.loginFailure(baseBean.msg);
                    }
                } else {
                    loginView.loginFailure("Login request failed");
                }
                loginView.hideDialog();
            }

            @Override
            public void onFailure(@NonNull Call<BaseBean<UserInfoResponseBean>> call, @NonNull Throwable t) {
                t.printStackTrace();
                loginView.loginFailure("Login request failed");
                loginView.hideDialog();
            }
        });
    }
}
